using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net;
using System.IO;
using System.Collections.Specialized;
using System.Xml;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Logic;


namespace oAuth
{


	public class oAuthClarizen : OAuthBase
	{
		public string GetTokenCookieName()
		{
			return "Clarizen_oauth_token";
		}
        public String Identifier { get; set; }

        public const String ClarizenSessionKey = "clarizen_session_id";
		public string GetSecretTokenCookieName()
		{
            return "Clarizen_oauth_token_secret";
		}

        public static oAuthClarizen Get()
        {
            var type = Logic.Constants.IsGmail ? "g" : "c";
            return new oAuthClarizen(ConfigurationManager.AppSettings["ClarizenToken_" + type], ConfigurationManager.AppSettings["ClarizenSecretToken_" + type], new HttpContextWrapper(HttpContext.Current));
        }

        public oAuthClarizen(string consumerKey, string consumerSecret, HttpContextBase context)
			: base(consumerKey, consumerSecret, context)
		{
			if (context.Request.Cookies[GetSecretTokenCookieName()] != null)
				this.TokenSecret = context.Request.Cookies[GetSecretTokenCookieName()].Value;
            if (context.Request.Cookies[GetTokenCookieName()] != null)
                this.Token = context.Request.Cookies[GetTokenCookieName()].Value;
		}

        public oAuthClarizen(string consumerKey, string consumerSecret, String token, String secret): base(consumerKey, consumerSecret, null)
        {
            this.ConsumerKey = consumerKey;
            this.ConsumerSecret = consumerSecret;
            this.Token = token;
            this.TokenSecret = secret;
        }

        public oAuthClarizen(List<Logic.GoogleGadget> gadgets, HttpRequest req)
        {
            Logic.GoogleGadget gadget = gadgets.Find(g => g.Key == req["oauth_consumer_key"]);
            if (gadget != null)
            {
                this.ConsumerKey = gadget.Key;
                this.ConsumerSecret = gadget.Secret;
            }
        }

		public override string GetRequestToken()
		{
            return "https://app.clarizen.com/Clarizen/Pages/Account/OAuthGetRequestToken.ashx";
		}
		public override string GetAuthorizeToken()
		{
            return "https://app.clarizen.com/Clarizen/Pages/Account/OAuthAuthorizeToken.ashx";
		}
		public override string GetAccessToken()
		{
            return "https://app.clarizen.com/Clarizen/Pages/Account/OAuthGetAccessToken.ashx";
		}

		protected const string OAuthVersion = "1.0";


        public override string AuthorizationLinkGet()
        {
            return AuthorizationLinkGet();
        }

		/// <summary>
		/// Get the link to Twitter's authorization page for this application.
		/// </summary>
		/// <returns>The url with a valid request token, or a null string.</returns>
		public string AuthorizationLinkGet(string goTo = "")
		{
            this.Token = null;
            this.TokenSecret = null;

			string ret = null;

            string response = oAuthWebRequest(Method.GET, GetRequestToken() + "?" + OAuthCallbackKey + "=" + UrlEncode(Constants.CurrentUrl + "/Oauth/Callback?" + Logic.Constants.googleID + "=" + Identifier + "&goto=" + UrlEncode(goTo)), String.Empty);
			//string response = oAuthWebRequest(Method.GET, GetRequestToken(), String.Empty);
			if (response.Length > 0)
			{
				//response contains token and token secret.  We only need the token.
				NameValueCollection qs = HttpUtility.ParseQueryString(response);
				if (qs["oauth_token"] != null)
					ret = GetAuthorizeToken() + "?oauth_token=" + qs["oauth_token"];
                if (qs["oauth_token_secret"] != null)
                    httpContext.Response.Cookies.Add(new HttpCookie(GetSecretTokenCookieName() + "_current", qs["oauth_token_secret"]));
			}
			return ret;
		}

		/// <summary>
		/// Exchange the request token for an access token.
		/// </summary>
		/// <param name="authToken">The oauth_token is supplied by Twitter's authorization page following the callback.</param>
		public override void AccessTokenGet()
		{
            string verifier = httpContext.Request.QueryString["oauth_verifier"];
            this.Token = httpContext.Request.QueryString["oauth_token"];
            //this.TokenSecret = HttpContext.Request.Cookies[GetSecretTokenCookieName() + "_current"].Value;
            var deletedCookie = new HttpCookie(GetSecretTokenCookieName() + "_current");
            deletedCookie.Expires = DateTime.Now.AddDays(-1);
            httpContext.Response.Cookies.Add(deletedCookie);

			string response = oAuthWebRequest(Method.GET, GetAccessToken(), String.Empty);

			if (response.Length > 0)
			{
				//Store the Token and Token Secret
				NameValueCollection qs = HttpUtility.ParseQueryString(response);
				if (qs["oauth_token"] != null)
				{
					this.Token = qs["oauth_token"];
				}
				if (qs["oauth_token_secret"] != null)
				{
					this.TokenSecret = qs["oauth_token_secret"];
				}
			}
		}


        public String GetSessionKey()
        {
            this.TokenSecret = "";
            var res = oAuthWebRequest(OAuthBase.Method.GET, "https://app.clarizen.com/Clarizen/Pages/Account/Login.ashx", String.Empty);
            NameValueCollection qs = HttpUtility.ParseQueryString(res);
            return qs[ClarizenSessionKey];
        }
    }
}
